import config from '@/config.js'
import {
	getStorage,
	removeStorage,
} from '@/util/auth.js';
import Vue from 'vue'
export default function(parameter) {
	parameter.header = {};
	const token = getStorage('token');
	if (token) {
		parameter.header['token'] = token;
	}
	const position = getStorage('position');
	if (position) {
		parameter.header['areaId'] = position.areaId;
		parameter.header['cityId'] = position.cityId;
	}
	parameter.url = config.requestUrl + parameter.url
	return new Promise((resolve, reject) => {
		uni.request({
			...parameter,
			success(e) {
				uni.hideLoading()
				if (e.statusCode != 200) {
					uni.showToast({
						title: '请求失败',
						icon: 'none',
						mask: true,
					})
					reject();
				} else {
					const response = e.data;
					switch (response.code) {
						case 200:
							resolve(response.data);
							break;
						case 405:
							uni.showToast({
								title: '登录信息已过期，请重新登录',
								icon: 'none',
								mask: true,
								duration: 2000,
								success: () => {
									// Vue.prototype.$store.commit(
									// 	'user/SET_TOKEN', null)
									// Vue.prototype.$store.commit('user/SET_USER',
									// 	null)
									setTimeout(() => {
										uni.reLaunch({
											url: '/page_other/mine/mine'
										})
									}, 2000)
									removeStorage('token');
									removeStorage('user');
								}
							})

							break;
						case 403:
							uni.showToast({
								title: '暂无权限',
								icon: 'none',
								duration: 2000,
								mask: true,
								success() {
									setTimeout(() => {
										reject();
									}, 2000)
								}
							})
							break;
						case 500:
							uni.showToast({
								title: '系统开小差,请联系管理员',
								icon: 'none',
								duration: 2000,
								mask: true,
								success() {
									setTimeout(() => {
										reject();
									}, 2000)
								}
							})
							break;
						case 201:
							uni.showToast({
								title: response.msg,
								icon: 'none',
								duration: 2000,
								mask: true,
								success() {
									setTimeout(() => {
										reject();
										if (response.msg == '请设置支付密码') {
											uni.redirectTo({
												url: '/page_other/password/password'
											})
										}
									}, 2000)
								}
							})
							break;
						default:
							uni.showToast({
								title: response.msg,
								icon: 'none',
								duration: 2000,
								mask: true,
								success() {
									setTimeout(() => {
										reject();
									}, 2000)
								}
							})
							break;
					}
				}
			},
			fail() {
				uni.hideLoading().then(() => {
					uni.showToast({
						title: '请求失败',
						icon: 'none',
						mask: true,
						duration: 2000,
						success() {
							setTimeout(() => {
								reject();
							}, 2000)
						}
					})
				})
			}
		})
	})
}